package com.whf.android.jar.net.callback.rx;

import android.text.TextUtils;

import com.whf.android.jar.constants.BaseEntries;
import com.whf.android.jar.net.callback.IError;
import com.whf.android.jar.net.callback.IFailure;

import org.jetbrains.annotations.NotNull;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 网络回调
 *
 * @author 傅令杰
 * @version 2017/4/2
 */
public final class RxRequestCallbacks<T> implements Observer<BaseEntries<T>> {

    private final IRxSuccess<T> SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;

    public RxRequestCallbacks(IRxSuccess<T> success, IFailure failure, IError error) {
        this.SUCCESS = success;
        this.FAILURE = failure;
        this.ERROR = error;
    }


    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(@NotNull BaseEntries<T> t) {
        if (t.isOk()) {
            if (SUCCESS != null) {
                SUCCESS.onSuccess(t.getData());
            }
        } else {
            final String msg = t.getMsg();
            if (ERROR != null) {
                ERROR.onError(t.getCode(), TextUtils.isEmpty(msg) ? t.getMessage() : msg);
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (FAILURE != null) {
            FAILURE.onFailure();
        }
    }

    @Override
    public void onComplete() {

    }
}
